<?php
/**
 * 注册模块
 * 2019.3.11
 * xiaosu
 */
namespace app\api\controller;

use app\api\service\RegisterService;
use app\api\validate\RegisterValidate;

class RegisterController extends BaseController
{
	public $RegisterService;
	public function __construct()
	{
		$this->RegisterService = new RegisterService();
	}
	/**
	 * 注册
	 */
	public function register()
	{
		$data = input('post.');

		$register = new RegisterValidate();

		$result = $register->check($data);
		if (true !== $result) {
			$this->ApiResult(false,10001,$register->getError());	
		}
		$arr = [];
		if ($data['invitation']) {//获取邀请人的信息
			$invitation = $this->RegisterService->getInvitation($data['invitation']);
			if ($invitation === false) {
				$this->ApiResult(false,10001,'邀请人不存在');
			}
			if ($invitation['volume'] == 0) {
				$this->ApiResult(false,10001,'推荐人需自购1台，有推荐资格');
			}
			$arr['first_leader'] = $invitation['user_id'];
			$arr['second_leader'] = $invitation['first_leader'];
		}
		
		$arr['mobile']       = $data['mobile'];
		$arr['user_name']    = $data['mobile'];
		$arr['nick_name']    = $data['mobile'];
		$arr['password']     = password_hash($data['password'],PASSWORD_DEFAULT);
		$arr['province']     = $data['province'];
		$arr['city']         = $data['city'];
		$arr['area']         = $data['area'];
		$arr['create_time']  = time();

		$res = $this->RegisterService->addUser($arr);
		if (false !== $res) {
			$this->ApiResult(true,10000,'注册成功');
		} else {
			$this->ApiResult(false,10001,'注册失败');
		}
	}
	/**
	 * 登录
	 */
	public function login()
	{
		$mobile = input('mobile');
		$password = input('password');

		if (empty($mobile) || empty($password)) {
			$this->ApiResult(false,10001,'参数错误');
		}
		if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
			$this->ApiResult(false,10001,'手机格式错误');
		}

		$user_info = $this->RegisterService->getUserInfo($mobile);
		if ($user_info['account_status'] == 1) {
			$this->ApiResult(false,10001,'账号已冻结');
		}
		if (!password_verify($password, $user_info['password'])) {
			$this->ApiResult(false,10001,'密码错误');
		}
		$token = md5(time().cmf_random_string(8));

		$update_login = $this->RegisterService->updateUser(['mobile' => $mobile],['token' => $token,'last_login' => time()]);

		$user_info['token'] = $token;
		$user_info['set_pay_code'] = 0;

		if (empty($user_info['pay_code'])) {
			$user_info['set_pay_code'] = 1;
		}
		
		unset($user_info['password']);
		unset($user_info['first_leader']);
		unset($user_info['second_leader']);
		unset($user_info['iden_card']);
		$user_info['level_name'] = config('member_level')[$user_info['level']];
		
		$this->ApiResult(true,10000,'登录成功',$user_info);

	}
	/**
	 * 验证短信验证码
	 */
	public function checkCode()
	{
		$mobile = input('mobile');
		$type = input('type');//1-注册，2-忘记登录密码,3-忘记支付密码
		if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
			$this->ApiResult(false,10001,'手机格式错误');
		}
		$check = $this->RegisterService->checkMobile($mobile,$type);

		if (false === $check['status']) {
			$this->ApiResult(false,10001,$check['msg']);	
		}

		$code = rand(100000,999999);
		//发送验证码
		$send_code = $this->sendCode($mobile,$code);
		if ($send_code === false) {
			$this->ApiResult(false,10001,'发送失败');
		}

		$time = time();
		$res = $this->RegisterService->addCode(['mobile' => $mobile, 'code' => $code, 'create_time' => $time, 'scene' => $type, 'expire_time' => $time+300]);

		if (false !== $res) {
			$this->ApiResult(true,10000,'发送成功');
		} else {
			$this->ApiResult(false,10001,'发送失败');
		}
	}
	/**
	 * 地址 
	 */
    public function address()
    {
    	$address = cache('address');
    	if (empty($address)) {
    		$address = $this->RegisterService->getAddress();
    		cache('address', $address, 3600);
    	}
    	$this->ApiResult(true,10000,'获取成功',$address);	
    }
    /**
     * 忘记密码
     */
    public function forgetPassword()
    {
    	$forget_cache = input('forget_cache');//进行第二步验证的缓存
    	if (empty($forget_cache)) {//操作第一步

    		$mobile = input('mobile');
    		$code = input('code');
			if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
				$this->ApiResult(false,10001,'手机格式错误');
			}

    		$check = $this->RegisterService->checkCode($mobile,$code,$type=2);
    		if ($check['status'] !== true) {
    			$this->ApiResult(false,10001,$check['msg']);
    		}
    		cache($check['key'],$mobile,3600);//存入缓存为了第二步
    		$this->ApiResult(true,10000,$check['msg'],['forget_cache' => $check['key']]);
    	} else {

    		$mobile = cache($forget_cache);//通过缓存获取手机号码
    		if (empty($mobile)) {//操作过期
    			$this->ApiResult(false,10002,'操作过期');
    		}
    		$password = input('password');
    		$second_password = input('second_password');

    		if (empty($password) || empty($second_password)) {
    			$this->ApiResult(false,10001,'密码不能为空');
    		}
			if(!preg_match("/^(\w*(?=\w*\d)(?=\w*[A-Za-z])\w*){6,16}$/", $password)){
				$this->ApiResult(false,10001,'密码要6-16（英文/数字/符号）至少两种或下划线组合');
			}
			if ($password !== $second_password) {
				$this->ApiResult(false,10001,'两次密码不一致');
			}

			$res = $this->RegisterService->updateUser(['mobile' => $mobile],['password' => password_hash($password,PASSWORD_DEFAULT)]);
			if (false !== $res) {
				$this->ApiResult(true,10000,'修改成功,请重新登录');
			} else {
				$this->ApiResult(false,10001,'修改失败');
			}
    	}

    }

	 /**
     * 发送短信验证码
     * $mobile 手机号码
     */
    protected function sendCode($mobile,$code){
   
        $tpl = 'TP1901254';
        
        $host = "http://dingxin.market.alicloudapi.com";
        $path = "/dx/sendSms";
        $method = "POST";
        $appcode = "eaf8824a23384736b8cde69e89073829";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "mobile=".$mobile."&param=code:".$code."&tpl_id=".$tpl;
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $str = curl_exec($curl);
        $preg= '/{[\s\S]*?}/i';
        preg_match_all($preg,$str,$res);
        $res = json_decode($res[0][0],true);
        if($res['return_code'] == '00000'){
            return true;
        }else{
            return false;
        }
    }

}